document.addEventListener('DOMContentLoaded', () => {
    const searchBox = document.getElementById('searchBox');

    refresh([]);

    // 内容发生改变
    searchBox?.addEventListener('input', async (e: any) => {
        const query = e.target.value.trim();
        const results = await window.exposeAPI.searchContentChange(query);
        refresh(results);
        refreshSelection();
    });

    // 当搜索框失去焦点时，隐藏主窗口
    searchBox?.addEventListener('blur', e => { window.exposeAPI.hideWindow(); });

    // 当主窗口显示时，使搜索框获得焦点
    window.exposeAPI.onMainWindowShow(() => { searchBox?.focus(); });
    window.exposeAPI.onSelectionChange((index: number) => { setSelection(index); });
    window.exposeAPI.onResetFace(() => { resetFace(); });
});

function addResult(item: any) {
    const resultsContainer = document.getElementById('resultsContainer');
    if (resultsContainer == null) return;
    resultsContainer.innerHTML += `
        <div class = 'result'>
            <div class = 'name'>${item.name}</div>
            <div class = 'describe'>${item.param}</div>
        </div>
    `;
}

/**刷新界面 */
function refresh(results: any[]) {
    const resultsContainer = document.getElementById('resultsContainer');
    if (resultsContainer == null) return;

    // 显示搜索结果
    resultsContainer.innerHTML = '';
    for (let item of results) addResult(item);
    // 没有搜索结果就隐藏容器
    resultsContainer.className = results.length == 0 ? 'hidden-element' : '';

    // 没有搜索结果时不显示水平线
    const hr = document.getElementsByTagName('hr').item(0);
    if (hr == null) return;
    hr.className = results.length == 0 ? 'hidden-element' : '';

    // 根据显示内容设置窗口大小
    const body = document.getElementsByTagName('body').item(0);
    if (body == null) return;
    window.exposeAPI.setWindowHeight(body.getBoundingClientRect().height);
}

async function refreshSelection() {
    let index = await window.exposeAPI.getSelectionIndex();
    setSelection(index);
}

function resetFace() {
    const searchBox = <HTMLInputElement>document.getElementById('searchBox');
    if (searchBox == null) return;
    searchBox.value = '';

    refresh([]);
}

function setSelection(index: number) {
    const resultsContainer = document.getElementById('resultsContainer');
    if (resultsContainer == null) return;
    for (let i = 0; i < resultsContainer.children.length; i++) {
        if (i == index) resultsContainer.children[i].className = 'result selected';
        else resultsContainer.children[i].className = 'result';
    }
}
